<template>
  <!-- <lay-button type="primary" @click="changedialogVisible">填报信息</lay-button> -->
  <lay-layer v-model="dialogVisible" :title="dialogTitle" :area="['75%',]" :close="handleClose" :btn="action">
    <div style="padding: 20px;">
      <lay-form :model="form" ref="formRef" :rules="rules" isLabelTooltip>
        <lay-form-item label="资源ID" prop="id" mode="inline" v-if="form.id != -1">
          <lay-input v-model="form.id" :disabled="true"></lay-input>
        </lay-form-item>
        <lay-form-item label="省" prop="province" required mode="inline">
          <lay-input v-model="form.province"></lay-input>
        </lay-form-item>
        <lay-form-item label="市" prop="city" required mode="inline">
          <lay-input v-model="form.city"></lay-input>
        </lay-form-item>
        <lay-form-item label="县、区" prop="county" required mode="inline">
          <lay-input v-model="form.county"></lay-input>
        </lay-form-item>
        <lay-form-item label="乡、镇" prop="town" mode="inline">
          <lay-input v-model="form.town"></lay-input>
        </lay-form-item>
        <lay-form-item label="村" prop="village" mode="inline">
          <lay-input v-model="form.village"></lay-input>
        </lay-form-item>
        <br />
        <lay-form-item label="植被生态区" prop="vegetation_ecological_zone" required mode="inline">
          <lay-select v-model="form.vegetation_ecological_zone" placeholder="请选择">
            <lay-select-option v-for="item in vegetationEcologicalZoneList" :key="item.id" :value="item.id"
              :label="item.name"></lay-select-option>
          </lay-select>
        </lay-form-item>

        <lay-form-item label="生态工程区" prop="ecological_engineering_zone" required mode="inline">
          <lay-select v-model="form.ecological_engineering_zone" placeholder="请选择">
            <lay-select-option v-for="item in ecologicalEngineeringZoneList" :key="item.id" :value="item.id"
              :label="item.name"></lay-select-option>
          </lay-select>
        </lay-form-item>

        <lay-form-item label="森林类别" prop="forest_class" required mode="inline">
          <lay-select v-model="form.forest_class" placeholder="请选择">
            <lay-select-option v-for="item in forestClassList" :key="item.id" :value="item.id"
              :label="item.level ? item.name + '(' + item.level + ')' : item.name"></lay-select-option>
          </lay-select>
        </lay-form-item>

        <lay-form-item label="生态分区" prop="ecological_zone" required mode="inline">
          <lay-select v-model="form.ecological_zone" placeholder="请选择">
            <lay-select-option v-for="item in ecologicalZoneList" :key="item.id" :value="item.id"
              :label="item.name"></lay-select-option>
          </lay-select>
        </lay-form-item>

        <lay-form-item label="生态分区2" prop="ecological_zone_2" required mode="inline">
          <lay-select v-model="form.ecological_zone_2" :disabled="true">
            <lay-select-option :value="form.ecological_zone_2" :label="form.ecological_zone_2"></lay-select-option>
          </lay-select>
        </lay-form-item>

        <lay-form-item label="优势树种" prop="dominant_tree_species" required mode="inline">
          <lay-select v-model="form.dominant_tree_species" placeholder="请选择">
            <lay-select-option v-for="item in treeSpeciesList" :key="item.id" :value="item.id"
              :label="item.name"></lay-select-option>
          </lay-select>
        </lay-form-item>

        <lay-form-item label="起源" prop="origin" required mode="inline">
          <lay-select v-model="form.origin" placeholder="请选择">
            <lay-select-option v-for="item in originList" :key="item.id" :value="item.id"
              :label="item.name"></lay-select-option>
          </lay-select>
        </lay-form-item>

        <lay-form-item label="年龄组" prop="age_group" required mode="inline">
          <lay-select v-model="form.age_group" placeholder="请选择">
            <lay-select-option v-for="item in ageGroupList" :key="item.id" :value="item.id"
              :label="item.name"></lay-select-option>
          </lay-select>
        </lay-form-item>
        <br />
        <lay-form-item label="面积(ha)" prop="area" mode="inline">
          <lay-input-number v-model="form.area" position="right" :min="0" :precision="2"></lay-input-number>
        </lay-form-item>
        <lay-form-item label="蓄积(m³)" prop="stock" mode="inline">
          <lay-input-number v-model="form.stock" position="right" :min="0" :precision="2"></lay-input-number>
        </lay-form-item>
        <lay-form-item label="每公顷蓄积(m³/ha)" prop="stock_per_ha" mode="inline">
          <lay-input-number v-model="form.stock_per_ha" position="right" :min="0" :precision="2"></lay-input-number>
        </lay-form-item>
        <lay-form-item label="平均树高(m)" prop="mean_tree_height" mode="inline">
          <lay-input-number v-model="form.mean_tree_height" position="right" :min="0" :precision="2"></lay-input-number>
        </lay-form-item>
        <lay-form-item label="平均胸径(cm)" prop="mean_dbh" mode="inline">
          <lay-input-number v-model="form.mean_dbh" position="right" :min="0" :precision="2"></lay-input-number>
        </lay-form-item>
        <lay-form-item label="林分生物量" prop="forest_stand_biomass" mode="inline">
          <lay-input-number v-model="form.forest_stand_biomass" position="right" :min="0"
            :precision="2"></lay-input-number>
        </lay-form-item>
        <lay-form-item label="系数" prop="coefficient" mode="inline">
          <lay-input-number v-model="form.coefficient" position="right" :min="0" :precision="2"></lay-input-number>
        </lay-form-item>
        <lay-form-item label="备注" prop="remark">
          <lay-input v-model="form.remark"></lay-input>
        </lay-form-item>
      </lay-form>
    </div>
  </lay-layer>
</template>

<script setup>
import { ref, reactive, watch, defineProps, defineEmits } from 'vue'
import { layer } from '@layui/layui-vue'
import api from '@/api';


// 下拉选择列表
const vegetationEcologicalZoneList = ref([]);
const ecologicalEngineeringZoneList = ref([]);
const forestClassList = ref([]);
const ecologicalZoneList = ref([]);
const treeSpeciesList = ref([]);
const originList = ref([]);
const ageGroupList = ref([]);

const getList = async () => {
  vegetationEcologicalZoneList.value = (await api.get('field/vegetationecologicalzone/list')).data.filter(item => item.status);
  ecologicalEngineeringZoneList.value = (await api.get('field/ecologicalengineeringzone/list')).data.filter(item => item.status);
  forestClassList.value = (await api.get('field/forestclass/list')).data.filter(item => item.status);
  ecologicalZoneList.value = (await api.get('field/ecologicalzone/list')).data.filter(item => item.status);
  treeSpeciesList.value = (await api.get('field/treespecies/list')).data.filter(item => item.status);
  originList.value = (await api.get('field/origin/list')).data.filter(item => item.status);
  ageGroupList.value = (await api.get('field/agegroup/list')).data.filter(item => item.status);
}

const emits = defineEmits(['update:modelValue', 'initDataList'])
const props = defineProps(
  {
    id: { type: Number, default: -1, required: true },
    dialogTitle: { type: String, default: '', required: true },
    dialogVisible: { type: Boolean, default: false, required: true }
  }
)

const form = ref({
  id: -1,
  province: "广西", city: "", county: "", town: "", village: "",
  vegetation_ecological_zone: "", ecological_engineering_zone: "",
  forest_class: "", ecological_zone: "", ecological_zone_2: "",
  dominant_tree_species: "", origin: "", age_group: "",
  area: "", stock: "", stock_per_ha: "", mean_tree_height: "",
  mean_dbh: "", forest_stand_biomass: "", coefficient: "",
  remark: "",
})

// keep a copy of initial values for reset (deep clone)
const _initialForm = JSON.parse(JSON.stringify(form.value))
const formRef = ref(null)
const rules = ref({
  name: [
    { required: true, message: '请输入名称！' },
    { type: 'string', message: '名称须为字符串!', trigger: 'blur' }
  ],
  value: [
    { required: true, message: '请输入数值！' },
    // { type: 'number', message: '必须为数字', trigger: 'blur' },
  ]
})

const dialogVisible = ref(false);

const handleClose = () => {
  emits('update:modelValue', false)
  // treeId.value = null
}
const getObj = async (obj_id) => {
  await api.get('resource/get/resource?id=' + obj_id).then((res) => {
    console.log('@resource res', res)
    if (res.code == 200) {
      form.value = res.data;

    } else {
      form.value = JSON.parse(JSON.stringify(_initialForm))
    }
  })
  form.value.ecological_zone_2 = form.value.ecological_zone_name + form.value.forest_class_name;
}

watch(
  () => props.dialogVisible,
  () => {
    getList()
    let id = props.id;
    if (id != -1) {
      form.value.id = id;
      getObj(id);
      // 编辑，获取数据
    } else {
      // 新增，清空数据
      form.value = JSON.parse(JSON.stringify(_initialForm))
    }
  }
)

// 生态分区2自动拼接
watch(
  () => [form.value.ecological_zone, form.value.forest_class, form.value.id],
  ([zoneId, forestId]) => {
    const zoneLabel = ecologicalZoneList.value.find(item => item.id === zoneId)?.name || '';
    const forestLabel = forestClassList.value.find(item => item.id === forestId)?.name || '';
    form.value.ecological_zone_2 = zoneLabel + forestLabel;
  },
)

const action = ref([
  {
    text: "确认",
    callback: () => {
      formRef.value.validate(async (valid) => {
        if (valid) {
          console.log("字段校验成功！", form.value)
          await api.post("resource/save", form.value).then((res) => {
            if (res.code === 200) {
              layer.msg(res.msg, { icon: 1, time: 1000 });
              emits("initDataList")
              handleClose();
              // reset local form values (avoid relying on component API)
              form.value = JSON.parse(JSON.stringify(_initialForm))
            } else {
              layer.msg(res.msg, { icon: 2, time: 1000 });
            }
          })
        } else {
          console.log("字段校验失败！")
        }
      })
    }
  },
  {
    text: "取消",
    callback: handleClose
  }
])
</script>